<?php


namespace App\Repositories\Seller;


use App\Models\Finance;
use App\Models\User;
use App\Models\UserTransaction;
use App\Repositories\BaseRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UserTransactionRepository extends BaseRepository
{

    /**
     * @return Model
     */
    public function model()
    {
        return new UserTransaction();
    }

    /**
     * @param User $user
     * @param float $money 充值金额
     * @param float $price 实付款
     * @param string $desc
     * @return mixed
     */
    public function topUp(User $user, float $money, $price=0.00,$desc = '充值')
    {
        return DB::transaction(function () use ($user, $money, $desc,$price) {
            $res = $user->increment('balance', $money);
            if (!$res) {
                DB::rollBack();
                return false;
            }
            $uuid = uuid('CZ_');
            $transcartion = $user->transactions()->create(
                [
                    'seller_id' => $user->seller_id,
                    'amount' => $money,
                    'desc' => $desc,
                    'price'=>$price,
                    'type'=>UserTransaction::TYPE_TOP_UP,
                    'sn'=>$uuid
                ]
            );
            if (!$transcartion) {
                DB::rollBack();
                return false;
            }
            if($price>0){
                $finace_desc = "用户【{$user->mobile}】充值，流水编号【{$uuid}】";
                FinanceRepository::add($user->seller_id,$price,$finace_desc,Finance::TYPE_TOP_UP);
            }
            return true;
        });
    }

    /**
     * @param User $user
     * @param float $money
     * @param string $desc
     * @return mixed
     */
    public function consume(User $user, float $money, $desc = '消费')
    {
        return DB::transaction(function () use ($user, $money, $desc) {
            $res = $user->decrement('balance', $money);
            if (!$res) {
                DB::rollBack();
                return false;
            }
            $uuid = uuid('XF_');

            $transcartion = $user->transactions()->create(
                [
                    'seller_id' => $user->seller_id,
                    'amount' => $money,
                    'desc' => $desc,
                    'type'=>UserTransaction::TYPE_CONSUME,
                    'sn'=>$uuid
                ]
            );
            if (!$transcartion) {
                DB::rollBack();
                return false;
            }
            return true;
        });
    }
}